#!/usr/bin/env python

import os
import sys
import pygame
import time
import math
from pygame.locals import *

from globals import *
from grid import GameGrid
from snake import Snake, BasicSnake
from ai import AI, AIGrid, AISnake

# pygame.init() causes delays upon quit due to SDL mixer on my system
# pygame.time.get_ticks will not work like this though
pygame.display.init()
pygame.font.init()

# print 'Warning, sound disabled'
if not pygame.font:
	print "Warning, fonts disabled"

# switches
displayVoronoi = False

# resources
bg = "grid-800x800.jpg"

screen = pygame.display.set_mode([XRES, YRES])

# using sprites might be a bit 
# overkill but i want to try it out
sprites = pygame.sprite.LayeredDirty()

# initialize grid with snakes
background = pygame.image.load(bg).convert()
grid = GameGrid((DIMX, DIMY))
#grid.addSnake(Snake(grid, True, (255, 255, 255), [[3, DIMY/2+2], [3, DIMY/2+1], [3, DIMY/2], [2, DIMY/2], [1, DIMY/2]], 50, str(0), RIGHT))
grid.addSnake(Snake(grid, True, (255, 255, 255), [(4, DIMY/2)], 10, str(0), RIGHT))
grid.addSnake(Snake(grid, False, (255, 150, 0), [(DIMX-4, DIMY/2)], 10, str(1), LEFT))
#grid.addSnake(Snake(grid, False, (255, 0, 255), [(DIMX-3, DIMY/2+4)], 100, str(2), LEFT))

# initialize wall sprites
for wallSprite in grid.wallSprites:
	sprites.add(wallSprite)
# initialize snake sprites
for snake in grid.snakes:
	for segmentSprite in snake.segmentSprites:
		sprites.add(segmentSprite)

clock = pygame.time.Clock() # not used atm

screen.blit(background, (0, 0))
pygame.display.update()

# initialize AI
walls = [[(0,0), (DIMX-1, 0)],
	 [(DIMX-1, 0), (DIMX-1, DIMY-1)], 
	 [(DIMX-1, DIMY-1), (0, DIMY-1)], 
	 [(0, DIMY-1), (0, 0)]]
ai = AI(walls, grid)

def gameover():
	return grid.isEmpty()

def displayTerritories():
	t1 = time.time()
	retSizes, gridMap = ai.getTerritories()
	t2 = time.time()

	colors = []
	for snake in grid.snakes:
		if snake.isAlive:
			colors.append(snake.color)

	drawRect = pygame.draw.rect
	gmap = grid.gmap
	log = math.log
	for x in xrange(DIMX):
		for y in xrange(DIMY):
			topleft = posInPixels ((x, y))
			if gridMap[x][y] == 0:
				if gmap[x][y].isEmpty():
					drawRect(screen, BGTILECOLOR, (topleft, (TILESIZE, TILESIZE)))
				continue
			n = log(gridMap[x][y], 2)
			index = int(n)
			if index == n:
				c = colors[index]
				color = (c[0] / 2, c[1] / 2, c[2] / 2)
				drawRect(screen, color, (topleft, (TILESIZE, TILESIZE)))
			else:
				drawRect(screen, BGTILECOLOR, (topleft, (TILESIZE, TILESIZE)))
	t3 = time.time()
	#print "time1:", 1000*(t2-t1)
	#print "time2:", 1000*(t3-t2)

TIMEPERMOVE = 100

"""
from datetime import datetime
startingTime = datetime.now()
ai.voronoiDebug()
print (datetime.now() - startingTime).microseconds / 1000.0
"""

voronoiSprites = []
while not gameover():

	if displayVoronoi: 
		displayTerritories()

	spriteRects = sprites.draw(screen)
	
	if displayVoronoi:
		pygame.display.update()
	else:
		pygame.display.update(spriteRects)
	sprites.clear(screen, background)
	
	t1 = time.time()
	ai.run(timelimit=TIMEPERMOVE) # timelimit not in use atm
	t2 = time.time()
	
	time2wait = int(TIMEPERMOVE-1000*(t2-t1))
	pygame.time.delay(time2wait)

	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
			sys.exit()
		if event.type == KEYDOWN:
			if event.key == K_ESCAPE:
				pygame.quit()
				sys.exit()
			if len(grid.snakes) == 0:
				continue
			if event.key == K_UP:
				grid.snakes[0].direction = UP
			if event.key == K_DOWN:
				grid.snakes[0].direction = DOWN
			if event.key == K_RIGHT:
				grid.snakes[0].direction = RIGHT
			if event.key == K_LEFT:
				grid.snakes[0].direction = LEFT
			if event.key == K_w:
				grid.snakes[1].direction = UP
			if event.key == K_d:
				grid.snakes[1].direction = RIGHT
			if event.key == K_s:
				grid.snakes[1].direction = DOWN
			if event.key == K_a:
				grid.snakes[1].direction = LEFT
	
	ai.moveBots()
	grid.update(sprites)
	ai.update()

pygame.quit()
sys.exit()
